package com.dc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dc.entity.Users;
import com.dc.service.UsersService;
import com.dc.service.impl.UsersServiceImpl;
import com.dc.tools.SendSms;
import com.google.gson.Gson;


/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UsersService us = new UsersServiceImpl();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 起始位置设置请求编码
		request.setCharacterEncoding("utf-8");
		
		//为了区分不同的请求，设置一个临时变量，根据不同变量的值来执行不同的方法
		String op = ""; //赋值为""
		if (request.getParameter("op")!=null) {
			op = request.getParameter("op");
		}
		//用户登录
		if ("user_login".equals(op)) {
			// 获取表单的内容，使用request对象的方法request.getParameter("参数名");
			String username = request.getParameter("username");
			System.out.println("username:" + username);
			String userpsw = request.getParameter("userpsw");
			System.out.println("userpsw:" + userpsw);
			Users u = us.login(username, userpsw);
			System.out.println(u);
			
			//获取输入的验证码
			String YZM=request.getParameter("YZM");//自己输入的验证码
			String randStr=(String) request.getSession().getAttribute("randStr");//随机生成的验证码
			if (YZM==null || !YZM.equals(randStr)) {//进行比对
				request.setAttribute("error", "验证码错误");
				request.getRequestDispatcher("user_login.jsp").forward(request, response);
				return;//跳出该程序，不执行下面的代码
			}

			if (u != null) {
				request.getSession().setAttribute("user", u);
				//用户选择记住密码
				if (request.getParameter("cksremember") != null) {
					//创建cookie，并设置其过期时间，存储到本地
					Cookie cookie1 = new Cookie("username", username);
					cookie1.setMaxAge(60 * 60);// 1h
					
					Cookie cookie2 = new Cookie("userpsw", userpsw);
					cookie2.setMaxAge(60 * 60);
					//将cookie的信息存储在本地: addCookie
					response.addCookie(cookie1);
					response.addCookie(cookie2);
				}
				//成功
				request.getRequestDispatcher("index.jsp").forward(request, response);				
			}else {
				//失败
				response.sendRedirect("user_login.jsp");
			}
		}else if ("ajaxsendmsg".equals(op)) {
			doAjaxSendMsg(request, response);
		}
	}	
			

	/**
	 * 发送短信的方法
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doAjaxSendMsg(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		String mobile = request.getParameter("mobile");
		System.out.println("mobile :" + mobile);
		// 2 生成一个六位随机数
		Random random = new Random();
		String scode = "";
		for (int i = 0; i < 6; i++) {
			scode += random.nextInt(10);
		}
		System.out.println("scode=" + scode);
		SendSms.sendSms(scode, mobile);
		// 我们以后再进行ajax请求的时候，我们希望返回结果是一个标准的格式
		// AjaxResponse: ->msg status data 等等
		// 目前可以简单处理，直接返回一个字符串

//		if (newsType == null) {
//			// ?没有找到
//			scode = "类型名称不存在,可以使用";
//		}
		// 3将list转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(scode);
		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 5.关闭
		outPrintWriter.close();
	}	   
		  
	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}
